<template>
	<view class="image-upload">
		<!-- <button v-if="isEdit" class="upload-btn" @click="chooseImage">选择图片</button> -->
		<image class="preview-image"  @click="chooseImage" :src="displayValue" @error="handleImageError" />
	</view>
</template>

<script>
	import urlConfig from '../../api/config.js';
	export default {
		props: {
			value: {
				type: String,
			},
			field: Object,
			isEdit: Boolean,
		},

		data() {
			return {
				imageUrl: '',
				defaultImage: '/no_image.png',
				urlConfig: urlConfig,
			}
		},
		
		emits: ['input'], // 声明 emit 事件

		computed: {
			// 使用 computed 属性处理 value 的默认值
			displayValue() {
				debugger;
				if (this.value) {
					return this.urlConfig + "/api/images/" + this.value;
				}
				return 'https://www.dtxtkj.com/app/images/image-upload.png';
			},
		},
		methods: {
			chooseImage() {
				if (!this.isEdit) {
					return;
				}
				uni.chooseImage({
					count: 1,
					success: (res) => {
						this.uploadImg(res.tempFilePaths[0], 1);
					},
				});
			},

			async uploadImg(filePath, token) {
				if (!filePath) {
					uni.showToast({
						title: '没有选中图片',
						icon: 'none'
					});
					return;
				}

				uni.showLoading({
					mask: true
				});

				await uni.uploadFile({
					url: this.urlConfig + "/api/images/upload", //后台地址
					filePath: filePath,
					name: 'file',
					success: uploadFileRes => {
						uni.hideLoading();
						if (uploadFileRes.statusCode === 200) {
							uni.showToast({
								title: '上传成功',
								icon: 'none'
							});
							let dataObj = JSON.parse(uploadFileRes.data);
							this.$emit("update-value", dataObj.filename);
						} else {
							uni.showToast({
								title: '上传失败',
								icon: 'none'
							});
						}
					},
				});
			},


			handleImageError(event) {
				this.value = this.defaultImage;
			},
		},
	};
</script>

<style scoped>
	.image-upload {
		width: 200rpx;
		height: 200rpx;
		align-items: center;
		/* border: 1px solid #f0f0f0; */
	}

	.upload-btn {
		flex: 2;
		height: 40px;
		line-height: 40px;
		font-size: 14px;
		border: 1px solid #ccc;
		border-radius: 4px;
		text-align: center;
	}

	.preview-image {
		width: 200rpx;
		height: 200rpx;
		argin-top: 10px;
	}
</style>